// pages/car/car.js
const
    app = getApp(),
    globalData = app.globalData,
    utils = require('../../utils/util'),
    api = require('../../api/index');
Page({

    /**
     * 页面的初始数据
     */
    data: {
        isIpx: globalData.isIpx,
        chooseAll: false,
        toast: {
            visible: false,
            test: ''
        },
        carList: [],
        status: 0,
        chooseArr: [], // 选中的商品列表
        isManage: false, // 管理（删除）
        deleteArr: [], // 删除数组
        banListArr: [], // 库存为0禁止被选择的项目
        chooseAll: false,
        imageBaseUri: globalData.imageBaseUri,
        agentInfo: {}, // 顾问信息
        obj:{
            currenetPageIndex: 1,
            pageSize: 10
        },
        isReachBott:true
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.reload()


    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.reload()

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {
        if(!this.data.isReachBott) return
        let page=this.data.obj.currenetPageIndex+1
        console.log(page)
        this.setData({
            obj:{
                currenetPageIndex:page,
                pageSize: 10
            }
        })
        this.getCartList(this.data.obj);
    },

    // 全选
    chooseAll() {
        this.setData({
            chooseAll: !this.data.chooseAll,
            chooseArr: [], // 全选之前chooseArr清空，防止本来有值，然后添加重复值
        })
        let carList = this.data.carList,
            chooseArr = this.data.chooseArr;

        if (this.data.chooseAll) {
            carList.forEach(item => {
                // 库存不为0的都展示选中状态
                if (item.Stock == 0) {
                    return
                }
                item.checked = true;
                if (item.checked) {
                    chooseArr.push(item)
                }
            });
            this.setData({
                carList,
                chooseArr
            })
        } else {
            carList.forEach(item => {
                // 库存不为0的都展示非选中状态
                if (item.Stock == 0) {
                    return
                }
                item.checked = false;
                if (!item.checked) {
                    chooseArr.splice(chooseArr.indexOf(item), 1)
                }
            })
            this.setData({
                carList,
                chooseArr
            })
        }

        this.getSum()
        // this.getDiscount()

        console.log(this.data.carList, 'carlist alllllll', this.data.chooseArr, 'chooseArr')

    },

    // 单选
    chooseItem(e) {
        console.log(e, 'e', this.data.carList, '一选择时的carlist')
        let index = e.currentTarget.dataset.index;
        let item = this.data.carList[index],
            carList = this.data.carList,
            chooseArr = this.data.chooseArr,
            banListArr = this.data.banListArr;

        // 图标的展示
        item.checked = !item.checked;
        carList[index] = item;
        this.setData({
            carList
        })

        if (item.checked) {
            chooseArr.push(item)
        } else {
            chooseArr.splice(chooseArr.indexOf(item), 1)
        }

        this.setData({
            chooseArr
        })

        console.log(this.data.carList, 'carList', this.data.chooseArr, 'chooseArr')

        // 是否所选择项目已经是全部
        if (this.data.chooseArr.length + this.data.banListArr.length == this.data.carList.length) {
            this.setData({
                chooseAll: true
            })
        } else {
            this.setData({
                chooseAll: false
            })
        }

        this.getSum();

    },

    // 计算总价
    getSum() {
        let sum = 0,
            chooseArr = this.data.chooseArr || [];
        let discount = 0;
        let disList = this.data.discountList || [];

        // 原价
        chooseArr.forEach(item => {
            sum += (item.GoodsPageDto.GoodsSpecDtos[0].Price) * Number(item.Num ? item.Num : 1)
        })

        console.log(chooseArr, 'chooseArr', disList, 'dislits')

        console.log(Math.round(disList[0].GreenPrice), '111', Math.round(disList[1].GreenPrice), '222')
        console.log(disList[0].GreenDiscount / 100, '333', disList[1].GreenDiscount / 100, '444');

        // 打折
        if (chooseArr.length && disList.length && !this.data.agentInfo.MemberGradeId) {
            // sum >= disList[0].GreenPrice / (disList[0].GreenDiscount / 100) && sum < disList[1].GreenPrice / (disList[1].GreenDiscount / 100)
            if (sum >= disList[0].GreenPrice && sum < disList[1].GreenPrice) {
                discount = sum * (disList[0].GreenDiscount / 100);
            } else if (sum >= disList[1].GreenPrice) {
                discount = sum * (disList[1].GreenDiscount / 100);
            }
        }

        this.setData({
            sum: sum.toFixed(1),
            discount: discount.toFixed(1)
        })
    },

    reload() {
        this.setData({
            status: 0,
            chooseArr: [],
            agentInfo: wx.getStorageSync('agentInfo') || {},
            obj:{
            currenetPageIndex: 1,
            pageSize: 10
        }
        })
        this.getCartList(this.data.obj);
        this.getDiscount();
    },

    // 获取购物车列表
    async getCartList(obj) {
        if (!utils.getLoginState()) {
            return utils.checkLoginState({
                routeUri: 3,
                uri: '/pages/car/car'
            });
        }
    
        try {
            let res = await api.cart.getCartList(obj),
                data = res.data.ResData || {},
                content = data.Items || [],
                banListArr = this.data.banListArr;
            console.log(res, '购物车列表')
            for (let i = 0; i < content.length; i++) {
                content[i].checked = false;

                for (let j = 0; j < content[i].GoodsPageDto && content[i].GoodsPageDto.GoodsSpecDtos.length; j++) {
                    if (content[i].GoodsSpecId == content[i].GoodsPageDto.GoodsSpecDtos[j].Id) {
                        content[i].GoodsSpecName = content[i].GoodsPageDto.GoodsSpecDtos[j].Name;
                        content[i].GoodsPageDto.Price = content[i].GoodsPageDto.GoodsSpecDtos[j].Price;
                    }
                }

                // 如果库存为0，则不能选择
                if (content[i].GoodsPageDto && content[i].GoodsPageDto.Stock == 0) {
                    banListArr.push(content[i])
                }
            }
            let isReachBott=content?content.length===0?false:true:false
            if(obj.currenetPageIndex!==1){
                content=[...this.data.carList,...content]
            }
            this.setData({
                cartCount: data.TotalItems || 0,
                carList: content || [],
                status: 2,
                banListArr,
                chooseArr: [], // 初始化
                chooseAll: false,
                sum: 0,
                isReachBott:isReachBott
            })


            console.log(this.data.carList, '购物车列表', this.data.chooseArr, 'this.data.chooseArr', this.data.banListArr, 'banListArr');

        } catch (e) {
            console.log(e, '获取购物侧列表失败')
            this.setData({
                status: 1
            })
        }
    },

    // 管理（删除）购物车
    manageCar() {
        this.setData({
            isManage: !this.data.isManage
        })
    },

    // 删除购物车
    async deleteGoods() {
        // 选中的项目为空，不操作
        if (this.data.chooseArr.length == 0) {
            return
        }
        console.log(this.data.chooseArr, 'chooseArr')
        let chooseArr = this.data.chooseArr,
            idsArr = [];
        chooseArr.forEach(item => {
            idsArr.push(item.Id)
        })
        console.log(idsArr, 'idsArr');
        try {
            let res = await api.cart.deleteCart(idsArr),
                data = res.data.ResData || {};
            console.log(res, '删除购物车成功')
            this.setData({
                toast: {
                    visible: true,
                    text: "删除成功"
                },
                chooseAll: false,
                obj:{
                    currenetPageIndex: 1,
                    pageSize: 10
                }
            })
            this.getCartList(this.data.obj);
        } catch (e) {
            console.log(e, '删除购物车失败')
        }
    },

    // 结算，去订单页面
    submit() {
        // 选中的项目为空，不操作
        if (this.data.chooseArr.length == 0) {
            return
        }
        console.log(this.data.chooseArr, '结算时选择的项目列表')
        // let text=''
        // for(let i=0;i<this.data.chooseArr.length;i++){
        //     let text2=`编码：${this.data.chooseArr[i].GoodsPageDto.Id} 数量：${this.data.chooseArr[i].Num}\n`
        //     text=text+text2
        // }
        // console.log(text)
        let chooseArrStr = encodeURIComponent(JSON.stringify(this.data.chooseArr));

        wx.navigateTo({
            url: `/pages/product/confirm/confirm?goods=${chooseArrStr}`,
        })

    },

    editNum(e) {
        let idx = e.currentTarget.dataset.index;
        let carList = this.data.carList,
            item = carList[idx];
        let num = e.detail.value;
        item.Num = num;
        carList[idx] = item;

        this.setData({
            carList
        })

    },

    checkNum(e) {
        let idx = e.currentTarget.dataset.index;
        let carList = this.data.carList,
            item = carList[idx];

        if (item.checked) {
            this.getSum()
        }
    },

    // 单项增加
    addOne(e) {
        let idx = e.currentTarget.dataset.index,
            // item = e.currentTarget.dataset.item,
            carList = this.data.carList,
            item = carList[idx];

        console.log(item, 'item')

        if (item.Num >= item.GoodsPageDto.GoodsSpecDtos[0].Stock) {
            this.setData({
                toast: {
                    visible: true,
                    text: '超过库存'
                },
            })
            item.Num = item.GoodsPageDto.GoodsSpecDtos[0].Stock;
        } else {
            item.Num = item.Num + 1;
        }

        carList[idx] = item

        this.setData({
            carList
        })
        if (item.checked) {
            this.getSum()
        }
    },

    // 单项减去
    subOne(e) {
        let idx = e.currentTarget.dataset.index,
            // item = e.currentTarget.dataset.item,
            carList = this.data.carList,
            item = carList[idx];

        console.log(item, 'item')

        if (item.Num <= 1) {
            this.setData({
                toast: {
                    visible: true,
                    text: '至少购买一个商品'
                },
            })
            item.Num = 1;
        } else {
            item.Num = item.Num - 1;
        }

        carList[idx] = item

        this.setData({
            carList
        })
        if (item.checked) {
            this.getSum()
        }
    },

    // 跳转
    toDetail(e) {
        wx.navigateTo({
            url: `/pages/product/detail/detail?id=${e.currentTarget.dataset.id}`,
        })
    },

    // 折扣信息
    async getDiscount() {
        try {
            let res = await api.order.getDiscount(),
                data = res.data || [];

            let discountList = data.splice(0, 2);
            console.log(res, '折扣信息')
            this.setData({
                discountList
            })

            this.getSum()

        } catch (e) {
            console.log(e, '折扣失败')
        }
    }

})